<template>
  <div class="category-brand-container">
    <el-card shadow="hover" class="mb-20">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="品牌管理" name="brand">
          <el-form :model="brandForm" ref="brandFormRef" label-width="100px" :rules="brandRules">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="品牌名称" prop="name">
                  <el-input v-model="brandForm.name" placeholder="请输入品牌名称" />
                </el-form-item>
                <el-form-item label="品牌描述" prop="description">
                  <el-input v-model="brandForm.description" type="textarea" placeholder="请输入品牌描述" />
                </el-form-item>
                <el-form-item label="品牌状态" prop="status">
                  <el-radio-group v-model="brandForm.status">
                    <el-radio :label="1">启用</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="品牌Logo" prop="logo">
                  <el-upload
                      class="avatar-uploader"
                      :show-file-list="false"
                      :before-upload="beforeLogoUpload"
                      :on-change="handleLogoChange"
                      :auto-upload="false"
                  >
                    <img v-if="logoUrl" :src="logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="分类选择" prop="categoryIds">
                  <el-cascader
                      v-model="brandForm.categoryIds"
                      :options="categoryOptions"
                      :props="{ checkStrictly: true, emitPath: true, value: 'id', label: 'name' }"
                      placeholder="请选择分类"
                      clearable
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="submitBrandForm">提交</el-button>
              <el-button @click="resetBrandForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="分类管理" name="category">
          <div class="operation-bar">
            <el-button type="primary" @click="handleAddCategory(0)" icon="Plus">添加一级分类</el-button>
            <el-button @click="exportCategories" icon="Download">导出Excel</el-button>
            <el-upload
                action=""
                :show-file-list="false"
                :before-upload="beforeExcelUpload"
                :on-change="importCategories"
                accept=".xlsx,.xls"
                style="display: inline-block; margin-left: 10px"
            >
              <el-button icon="Upload">导入Excel</el-button>
            </el-upload>
          </div>

          <el-table
              :data="categoryList"
              row-key="id"
              border
              default-expand-all
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              v-loading="loading"
              style="width: 100%; margin-top: 20px"
          >
            <el-table-column prop="name" label="分类名称" width="200" />
            <el-table-column prop="level" label="级别" width="100">
              <template #default="{ row }">
                <el-tag :type="getLevelTagType(row.level)">
                  {{ getLevelText(row.level) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="100" sortable />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-switch
                    v-model="row.status"
                    :active-value="1"
                    :inactive-value="0"
                    @change="handleStatusChange(row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="icon" label="图标" width="120">
              <template #default="{ row }">
                <el-image
                    v-if="row.icon"
                    :src="row.icon"
                    style="width: 40px; height: 40px"
                    :preview-src-list="[row.icon]"
                    hide-on-click-modal
                    preview-teleported
                />
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="handleAddCategory(row.level + 1, row.id)" v-if="row.level < 3">
                  添加子分类
                </el-button>
                <el-button size="small" type="primary" @click="handleEditCategory(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteCategory(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 分类添加/编辑对话框 -->
    <el-dialog
        v-model="categoryDialogVisible"
        :title="`${isEdit ? '编辑' : '添加'}${getLevelText(categoryForm.level)}分类`"
        width="600px"
    >
      <el-form :model="categoryForm" ref="categoryFormRef" label-width="100px" :rules="categoryRules">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input v-model="categoryForm.description" type="textarea" placeholder="请输入分类描述" />
        </el-form-item>
        <el-form-item label="分类图标" prop="icon">
          <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeIconUpload"
              :on-change="handleIconChange"
              :auto-upload="false"
          >
            <img v-if="categoryForm.icon || iconPreviewUrl" :src="iconPreviewUrl || categoryForm.icon" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序值" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="1" :step="10" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="categoryForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCategoryForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const activeTab = ref('brand')
const loading = ref(false)
const categoryDialogVisible = ref(false)
const isEdit = ref(false)
const iconPreviewUrl = ref('')

// 品牌表单相关
const brandFormRef = ref(null)
const brandForm = reactive({
  name: '',
  description: '',
  status: 1,
  logo: null,
  categoryIds: []
})
const logoUrl = ref('')
const categoryOptions = ref([])

const brandRules = {
  name: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  categoryIds: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

// 分类表单相关
const categoryFormRef = ref(null)
const categoryForm = reactive({
  id: null,
  name: '',
  description: '',
  icon: null,
  level: 1,
  parentId: 0,
  sort: 100,
  status: 1,
  iconFile: null
})

const categoryRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 分类列表
const categoryList = ref([])

// 获取分类数据
const fetchCategories = async () => {
  try {
    loading.value = true
    const res = await axios.get('/api/brand/brand/findCategory')
    if (res.data.code === 200) {
      // 构建树形结构
      const buildTree = (list, parentId = 0) => {
        return list
            .filter(item => item.parentId === parentId && item.isDeleted === 0)
            .map(item => ({
              ...item,
              children: buildTree(list, item.id)
            }))
      }
      categoryList.value = buildTree(res.data.data)

      // 同时更新级联选择器数据
      categoryOptions.value = buildTree(res.data.data)
    }
  } catch (error) {
    ElMessage.error('获取分类数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchCategories()
})

// 品牌相关方法
const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片格式!')
  }
  return isImage
}

const handleLogoChange = (file) => {
  brandForm.logo = file.raw
  const reader = new FileReader()
  reader.onload = e => {
    logoUrl.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const submitBrandForm = () => {
  brandFormRef.value.validate(async (valid) => {
    if (!valid) return
    const formData = new FormData()
    formData.append('brand', JSON.stringify({
      name: brandForm.name,
      description: brandForm.description,
      status: brandForm.status
    }))
    if (brandForm.logo) formData.append('logo', brandForm.logo)
    if (brandForm.categoryIds && brandForm.categoryIds.length > 0) {
      brandForm.categoryIds.forEach(id => formData.append('categoryIds', id))
    }
    try {
      const res = await axios.post('/api/brand/brand/addBrand', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      if (res.data.code === 200) {
        ElMessage.success('添加成功')
        resetBrandForm()
      } else {
        ElMessage.error(res.data.msg || '添加失败')
      }
    } catch (e) {
      ElMessage.error('请求失败')
    }
  })
}

const resetBrandForm = () => {
  brandFormRef.value?.resetFields()
  brandForm.logo = null
  logoUrl.value = ''
}

// 分类相关方法
const getLevelText = (level) => {
  return ['一级', '二级', '三级'][level - 1] || '未知'
}

const getLevelTagType = (level) => {
  return ['', 'success', 'warning', 'danger'][level] || 'info'
}

const handleAddCategory = (level, parentId = 0) => {
  isEdit.value = false
  categoryFormRef.value?.resetFields()
  Object.assign(categoryForm, {
    id: null,
    name: '',
    description: '',
    icon: null,
    level,
    parentId,
    sort: 100,
    status: 1,
    iconFile: null
  })
  iconPreviewUrl.value = ''
  categoryDialogVisible.value = true
}

const handleEditCategory = (row) => {
  isEdit.value = true
  Object.assign(categoryForm, {
    id: row.id,
    name: row.name,
    description: row.description,
    icon: row.icon,
    level: row.level,
    parentId: row.parentId,
    sort: row.sort,
    status: row.status,
    iconFile: null
  })
  iconPreviewUrl.value = ''
  categoryDialogVisible.value = true
}

const handleDeleteCategory = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除分类 "${row.name}" 吗?`, '提示', {
      type: 'warning'
    })
    const res = await axios.post('/api/brand/brand/delCategory', { id: row.id })
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchCategories()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const handleStatusChange = async (row) => {
  try {
    // 创建FormData对象
    const formData = new FormData();

    // 构建分类数据对象（只包含需要更新的id和status）
    const categoryData = {
      id: row.id,
      status: row.status
    };

    // 将JSON数据作为Blob添加到FormData（关键修改点）
    formData.append('category', new Blob([JSON.stringify(categoryData)], {
      type: 'application/json'
    }), 'data.json');

    // 发送请求（注意不手动设置Content-Type）
    const res = await axios.post('/api/brand/brand/updateCategory', formData, {
      headers: {
        // 不手动设置Content-Type，让浏览器自动处理为multipart/form-data
      }
    });

    if (res.data.code !== 200) {
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1;
      ElMessage.error(res.data.msg || '状态更新失败');
    }
  } catch (error) {
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1;
    console.error('状态更新失败:', error);
    ElMessage.error('状态更新失败');
  }
};

const beforeIconUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片格式!')
  }
  return isImage
}

const handleIconChange = (file) => {
  categoryForm.iconFile = file.raw
  const reader = new FileReader()
  reader.onload = e => {
    iconPreviewUrl.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const submitCategoryForm = () => {
  categoryFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      const formData = new FormData();

      // 构建分类数据对象（不要包含icon字段）
      const categoryData = {
        id: categoryForm.id,
        name: categoryForm.name,
        description: categoryForm.description,
        status: categoryForm.status
      };

      // 关键修改点1：确保正确添加JSON数据
      formData.append('category', new Blob([JSON.stringify(categoryData)], {
        type: 'application/json'
      }), 'data.json');

      // 关键修改点2：处理图片上传
      if (categoryForm.iconFile) {
        formData.append('icon', categoryForm.iconFile);
      } else if (isEdit.value && categoryForm.icon) {
        // 编辑时如果没有新图片，可以传空或忽略
        // 如果需要保持原图，可以不添加icon字段
      }

      // 调试：打印FormData内容
      for (let [key, value] of formData.entries()) {
        console.log(key, value instanceof Blob ? `${value.type} (Blob)` : value);
      }

      // 发送请求
      const res = await axios.post('/api/brand/brand/updateCategory', formData, {
        headers: {
          // 关键修改点3：不要手动设置Content-Type，让浏览器自动设置
          // 包括multipart boundary
        }
      });

      if (res.data.code === 200) {
        ElMessage.success('更新成功');
        categoryDialogVisible.value = false;
        fetchCategories();
      } else {
        ElMessage.error(res.data.msg || '更新失败');
      }
    } catch (error) {
      console.error('操作失败:', error);
      let errorMsg = error.response?.data?.message || error.message || '操作失败';

      if (error.response?.status === 415) {
        errorMsg = '请求格式错误：后端需要multipart/form-data格式';
      }

      ElMessage.error(errorMsg);
    }
  });
};

const exportCategories = async () => {
  try {
    const res = await axios.get('/api/brand/brand/exportCategories', {
      responseType: 'blob'
    })
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', 'categories.xlsx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

const beforeExcelUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
  }
  return isExcel
}

const importCategories = async (file) => {
  try {
    const formData = new FormData()
    formData.append('file', file.raw)
    const res = await axios.post('/api/brand/brand/importCategories', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    if (res.data.code === 200) {
      ElMessage.success('导入成功')
      fetchCategories()
    } else {
      ElMessage.error(res.data.msg || '导入失败')
    }
  } catch (error) {
    ElMessage.error('导入失败')
  }
}
</script>

<style scoped>
.category-brand-container {
  padding: 20px;
}

.mb-20 {
  margin-bottom: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 8px;
  margin-right: 10px;
  object-fit: contain;
}
</style>
